﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StringExtensions
{
    public class Command
    {
        readonly char[] paramsSeparator = {','};

        public string OriginalForm { get; private set; }
        public string Name { get; private set; }
        public string[] Parameters { get; private set; }

        private Int32 openingBracketIndex;
        private Int32 closingBracketIndex;

        public Command(string input)
        {
            this.OriginalForm = input.Trim();

            this.Parse();
        }

        private void Parse()
        {
            this.GetBracketsIndexes();

            this.Name = this.ParseName();
            this.Parameters = this.ParseParameters();
            this.TrimParams();
        }

        private string ParseName()
        {
            string name = this.OriginalForm.Substring(0, this.openingBracketIndex);

            return name;
        }

        private string[] ParseParameters()
        {
            Int32 paramsLength = this.closingBracketIndex - 1 - this.openingBracketIndex;

            string paramsOriginalForm = this.OriginalForm.Substring(this.openingBracketIndex + 1, paramsLength);

            string[] parameters = paramsOriginalForm.Split(paramsSeparator, StringSplitOptions.RemoveEmptyEntries);

            return parameters;
        }

        private void GetBracketsIndexes()
        {
            this.openingBracketIndex = this.OriginalForm.IndexOf("(");
            this.closingBracketIndex = this.OriginalForm.IndexOf(")");

            if (this.openingBracketIndex == -1 || this.closingBracketIndex == -1)
            {
                throw new IndexOutOfRangeException("Invalid command!");
            }
        }

        private void TrimParams()
        {
            for (int i = 0; i < this.Parameters.Length; i++)
            {
                this.Parameters[i] = this.Parameters[i].Trim();
            }
        }
    }
}
